package com.springboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Random;

/**
 * @author TANGSHUAI
 * @version 1.0
 * @date 2021-08-30 22:41
 */
@Controller
public class RedisController {

    @Autowired
    private RedisTemplate redisTemplate;


    @GetMapping("")
    public String index() {
        //设置值
        redisTemplate.opsForValue().set("name", "张三");
        //取值
        String name = (String) redisTemplate.opsForValue().get("name");
        System.out.println(name);
        return "index";
    }

    @PostMapping("/doseckill")
    public @ResponseBody
    boolean doseckill(String prodid) {
        Random random = new Random();
        String result="";
        for (int i=0;i<6;i++)
        {
            result+=random.nextInt(10);
        }
        boolean b = this.doSecKill(result, prodid);
        return b;
    }

    //秒杀过程
    public boolean doSecKill(String uid, String prodid)  {
        //1 uid和prodid非空判断
        if (uid == null || prodid == null) {
            return false;
        }

        //3 拼接key
        // 3.1 库存key
        String kcKey = "sk:" + prodid + ":qt";
        // 3.2 秒杀成功用户key
        String userKey = "sk:" + prodid + ":user";

        //开启事务
        redisTemplate.setEnableTransactionSupport(true);
        //监视库存
        redisTemplate.watch(kcKey);

        //4 获取库存，如果库存null，秒杀还没有开始
        String kc = String.valueOf(redisTemplate.opsForValue().get(kcKey)) ;
        if (kc == null) {
            System.out.println("秒杀还没有开始，请等待");
            return false;
        }

        // 5 判断用户是否重复秒杀操作
        if (redisTemplate.opsForSet().isMember(userKey, uid)) {
            System.out.println("已经秒杀成功了，不能重复秒杀");
            return false;
        }

        //6 判断如果商品数量，库存数量小于1，秒杀结束
        if (Integer.parseInt(kc) <= 0) {
            System.out.println("秒杀已经结束了");
            return false;
        }

        //7 秒杀过程
        //7.1 库存-1
        //redisTemplate.boundValueOps(kcKey).decrement(1);
        //7.2 把秒杀成功用户添加清单里面
        //redisTemplate.opsForSet().add(userKey, uid);
        //使用事务


        //2.使用事务
        redisTemplate.multi();

        //3.组队操作
        redisTemplate.boundValueOps(kcKey).decrement(1);

        redisTemplate.opsForSet().add(userKey, uid);

        //4.执行
        List<Object> exec = redisTemplate.exec();
        if(exec == null || exec.size()==0) {
            System.out.println("秒杀失败了....");
            return false;
        }
        System.out.println("秒杀成功了..");
        return true;
    }
}
